package com.wry.wry_test.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wry.wry_test.dao.entity.Hotel;
import com.wry.wry_test.dao.mapper.HotelMapper;
import com.wry.wry_test.model.HotelDoc;
import com.wry.wry_test.service.HotelService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: wangrongyi
 * @Date: 2024/8/6 13:57
 * @Description:
 */
@Service
@Slf4j
public class HotelServiceImpl extends ServiceImpl<HotelMapper, Hotel> implements HotelService {

    @Autowired
    private RestHighLevelClient esClient;

    @Override
    public List<Hotel> getAllHotel() {
        return baseMapper.selectList(null);
    }

    @Override
    public void getAllHotelToES() {
        List<Hotel> hotels = baseMapper.selectList(null);
        for (Hotel hotel : hotels) {
            HotelDoc doc = HotelDoc.transform(hotel);
            String json = JSON.toJSONString(doc);
            // 1.准备Request对象
            IndexRequest request = new IndexRequest("hotel").id(doc.getId().toString());
            // 2.准备Json文档
            request.source(json, XContentType.JSON);

            // 3.发送请求
            try {
                esClient.index(request, RequestOptions.DEFAULT);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }

    @Override
    public List<HotelDoc> queryDoc() {
        SearchRequest request = new SearchRequest("hotel");
        request.source().query(QueryBuilders.matchAllQuery());
        SearchResponse response;
        try {
            response = esClient.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        SearchHits searchHits = response.getHits();
        SearchHit[] hits = searchHits.getHits();
        if (hits.length == 0) {
            return null;
        }

        return Arrays.stream(hits).map(hit -> {
            String json = hit.getSourceAsString();
            return JSON.parseObject(json, HotelDoc.class);
        }).toList();
    }


}
